package org.xdq.springcloud.demo20191222.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xdq.base.DataStatusEnum;
import org.xdq.dto.RoleDto;
import org.xdq.exception.BusinessException;
import org.xdq.model.Module;
import org.xdq.springcloud.demo20191222.dao.RoleDao;
import org.xdq.springcloud.demo20191222.service.RoleService;
import org.xdq.util.Utils;

@Service
@Transactional //声明本业务类的所有方法都是事务性的
public class RoleServiceImpl implements RoleService {
	
	private int currId;
	
	@Autowired
	private RoleDao roleDao;

	
	@PostConstruct//定义初始化方法
	public void init() {
		currId = roleDao.findMaxId();
	}
	
	private synchronized Integer newId() {
		return ++currId;
	}
	

	@Override
	public Map<String,Object> getRoleList(RoleDto dto) {
		
		return Utils.getPage(dto, ()->{return roleDao.findRoleList(dto);});

	}

	@Override
	public void addRole(RoleDto dto) {
		dto.setRo_id(newId());
		roleDao.insertOneRole(dto);
		
	}

	@Override
	public void updateRole(RoleDto dto) {
		roleDao.updateOneRole(dto);
		
	}

	@Override
	public void deleteRole(Integer... id) {
		if(id==null || id.length==0) {
			throw new BusinessException("用户没有选择删除的数据！");
		}
		roleDao.deleteRoles(id);
		
	}

	@Override
	public String operateRole(String opr, Integer... id) {
		if(id==null || id.length==0) {
			throw new BusinessException("没有需要改变状态的数据！");
		}
		switch(opr) {
		case "confirm":
			roleDao.changeRoleStatus(DataStatusEnum.未确定.getCode(),DataStatusEnum.已确定.getCode(),id);
			return "确定成功！";
		case "use":
			roleDao.changeRoleStatus(DataStatusEnum.已确定.getCode(),DataStatusEnum.已启用.getCode(),id);
			roleDao.changeRoleStatus(DataStatusEnum.已禁用.getCode(),DataStatusEnum.已启用.getCode(),id);
			return "启用成功！";
		case "unuse":
			roleDao.changeRoleStatus(DataStatusEnum.已启用.getCode(),DataStatusEnum.已禁用.getCode(),id);
			return "禁用成功！";
		}
		throw new BusinessException("非法操作！");
	}

	@Override
	public List<Module> getAllModuleList() {
		// TODO Auto-generated method stub
		return roleDao.findAllModuleList();
	}

	@Override
	public List<Integer> getRoleModuleId(Integer ro_id) {
		// TODO Auto-generated method stub
		return roleDao.findRoleModuleId(ro_id);
	}

	@Override
	public void confirmRoleModule(Integer ro_id, Integer[] m_ids) {
		
		roleDao.deleteRoleModule(ro_id);
		if(m_ids == null || m_ids.length == 0) {
			return;
		}
		roleDao.insertRoleModule(ro_id,m_ids);
		
	}
	
	

}
